package org.jeecg.modules.innerApi.zhiYunSdApi.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.http.message.BasicNameValuePair;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.common.util.MathUtil;
import org.jeecg.modules.innerApi.common.requestDto.*;
import org.jeecg.modules.innerApi.common.responseDto.*;
import org.jeecg.modules.innerApi.zhiYunApi.util.ZhiyunApiResponse;
import org.jeecg.modules.innerApi.zhiYunSdApi.convert.ZySdRequestParamConvert;
import org.jeecg.modules.innerApi.zhiYunSdApi.convert.ZySdResponseRtnConvert;
import org.jeecg.modules.innerApi.zhiYunSdApi.requestVo.*;
import org.jeecg.modules.innerApi.zhiYunSdApi.responseVo.*;
import org.jeecg.modules.innerApi.zhiYunSdApi.service.IZhiyunSdfpService;
import org.jeecg.modules.innerApi.zhiYunSdApi.util.ZhiyunSdApiCallUtil;
import org.jeecg.modules.innerApi.zhiYunSdApi.util.ZhiyunSdApiResponse;
import org.jeecg.modules.system.service.ISysDictService;
import org.jeecg.modules.xxgx.common.enums.KplxEnum;
import org.jeecg.modules.xxgx.common.enums.KpzdztEnum;
import org.jeecg.modules.xxgx.hzsqgl.vo.CsXxHzsqjsPage;
import org.jeecg.modules.xxgx.kpzdgl.entity.CsXxKpzd;
import org.jeecg.modules.xxgx.kpzdgl.service.ICsXxKpzdService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 新时代智云数电开票接口服务
 */
@Service
public class ZhiyunSdfpServiceImpl implements IZhiyunSdfpService {
    @Autowired
    ZhiyunSdApiCallUtil zhiyunSdApiCallUtil;
    @Autowired
    ICsXxKpzdService kpzdService;

    @Autowired
    private ISysDictService sysDictService;

    public static enum APIURL {
        fpkj("全电蓝票开具接口", "/qdjk/fullExteriorInvoke/blueTicket"),
        getFaceState("获取是否需要人脸识别", "/qdjk/fullApplets/queryFaceAuthState"),
        faceImg("获取人脸二维码", "/qdjk/fullExteriorInvoke/getFaceImg"),
        login("登录电票平台", "/qdjk/fullExteriorInvoke/loginDppt"),
        creditLine("授信额度查询", "/qdjk/allElectricInvoice/getCreditLine"),
        getCompanyMsg("企业风险查询", "/qdjk/allElectricInvoice/getCompanyMsg"),
        getInvoicePdfOfd("获取版式文件", "/qdjk/fullExteriorInvoke/getInvoicePdfOfd"),
        hzxxbsq("申请全电票红字信息表", "/qdjk/fullExteriorInvoke/hzxxbsq"),
        hzxxbcx("撤销红字信息表", "/qdjk/fullExteriorInvoke/hzxxbcx"),
        hzxxbtb("红字信息表同步", "/qdjk/fullExteriorInvoke/hzxxbtb"),
        hzxxbNotarize("全电红字信息表确认", "/qdjk/fullExteriorInvoke/hzxxbNotarize"),
        queryHzxxb("查询红字信息表", "/qdjk/fullExteriorInvoke/queryHzxxb"),
        obtainNoticNumber("获取全电纸质发票代码号码", "/qdjk/fullExteriorInvoke/obtainNoticNumber"),
        hzfpkj("全电票开负数发票", "/qdjk/fullExteriorInvoke/hzfpkj"),
        cxkxffp("查询可修复的发票数据", "/qdjk/fullExteriorInvoke/invoiceQuery"),
        fjxx("附加信息业务操作", "/qdjk/fullExteriorInvoke/fjxxBusiness");
        private final String desc;//描述
        private final String url;//值

        APIURL(String desc, String url) {
            this.desc = desc;
            this.url = url;
        }
    }

    /**
     * 根据智云返回结果判断是否登录掉线
     */
    public void updateZdzt(CsXxKpzd kpzd, ZhiyunSdApiResponse response) {
        try {
            if (kpzd != null && response != null) {
                String zxzt = kpzd.getZxzt();
                if (response.getCode().equals(CommonConstant.DPPT_DL_SX)) {//登录失效
                    if (StringUtils.isEmpty(zxzt) || zxzt.equals(KpzdztEnum.zx.getValue())) {
                        kpzd.setZxzt(KpzdztEnum.lx.getDesc());
                        kpzdService.updateById(kpzd);
                    }
                } else if (response.getCode().equals(CommonConstant.SC_OK_200)) {
                    if (StringUtils.isEmpty(zxzt) || zxzt.equals(KpzdztEnum.lx.getValue())) {
                        kpzd.setZxzt(KpzdztEnum.zx.getValue());
                        kpzdService.updateById(kpzd);
                    }
                }
            }
        } catch (Exception e) {

        }
    }

    /**
     * 根据智云返回结果判断是否登录掉线
     */
    public void updateZdzt(CsXxKpzd kpzd, String response) {
        try {
            if (kpzd != null && response != null) {
                String zxzt = kpzd.getZxzt();
                if (StringUtils.isNotEmpty(response)) {
                    JSONObject json = JSON.parseObject(response);
                    if (json.containsKey("code")) {
                        Integer code = json.getIntValue("code");
                        if (code.equals(CommonConstant.DPPT_DL_SX)) {//登录失效
                            if (org.apache.commons.lang3.StringUtils.isEmpty(zxzt) || zxzt.equals(KpzdztEnum.zx.getValue())) {
                                kpzd.setZxzt(KpzdztEnum.lx.getDesc());
                                kpzdService.updateById(kpzd);
                            }
                        } else if (code.equals(CommonConstant.SC_OK_200)) {
                            if (StringUtils.isEmpty(zxzt) || zxzt.equals(KpzdztEnum.lx.getValue())) {
                                kpzd.setZxzt(KpzdztEnum.zx.getValue());
                                kpzdService.updateById(kpzd);
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {

        }
    }

    /**
     * 全电开票接口
     *
     * @param invoiceParam
     * @return
     */
    @Override
    public InvoiceRtn invoice(InvoiceParam invoiceParam) {
        String sdjk_use_test = sysDictService.queryDictTextByKey("xxparams", "sdjk_use_test");
        InvoiceRtn invoiceRtn = null;
        if (KplxEnum.ZSFP.getValue().equals(invoiceParam.getKplx())) {
            //转换开票参数
            SdQdlpkjjkrc11Param param = ZySdRequestParamConvert.invoiceParamConvert(invoiceParam);
            ZhiyunSdApiResponse response;
            if (!"1".equals(sdjk_use_test)) {
                response = zhiyunSdApiCallUtil.request(APIURL.fpkj.url, param, invoiceParam.getKpzd().getDzswjzh());
            } else {
                //cwgx todo:全电正数模拟数据
                //----------start------------
                String responseData = "{\"fphm\":\"23412000000036512345\",\"Kprq\":\"" + DateUtils.now() + "\"}";
                response = new ZhiyunSdApiResponse();
                response.setCode(200);
                response.setMsg("发票开具成功（模拟数据）");
                response.setData(JSON.parseObject(responseData));
                //----------end------------
            }

            //更新终端对应的电票平台在线状态
            updateZdzt(invoiceParam.getKpzd(), response);
            //转换开票结果
            invoiceRtn = ZySdResponseRtnConvert.sdfpRtnConvert(response);
            if (invoiceRtn.getSuccess()) {
                invoiceRtn.getData().setFpsqlsh(invoiceParam.getFpsqlsh());
                invoiceRtn.getData().setFplxdm(invoiceParam.getFplxdm());
                invoiceRtn.getData().setHjje(invoiceParam.getHjje());
                invoiceRtn.getData().setHjse(invoiceParam.getHjse());
                invoiceRtn.getData().setJshj(MathUtil.add(invoiceParam.getHjje(), invoiceParam.getHjse()));
            }
        } else if (KplxEnum.FSFP.getValue().equals(invoiceParam.getKplx())) {
            //负数发票开具
            HzfpkjParam param = ZySdRequestParamConvert.hzfpkjParamConvert(invoiceParam);
            SdQdpkfsfpcc14Rtn sdQdpkfsfpcc14Rtn = this.hzfpkj(param);
            invoiceRtn = new InvoiceRtn();
            if (sdQdpkfsfpcc14Rtn.getSuccess()) {
                invoiceRtn.setCode(String.valueOf(CommonConstant.SC_OK_200));
                invoiceRtn.setSuccess(true);
                InvoiceRtn.InvoiceRtnData rtnData = new InvoiceRtn.InvoiceRtnData();
                BeanUtils.copyProperties(sdQdpkfsfpcc14Rtn, rtnData);
                rtnData.setFpsqlsh(invoiceParam.getFpsqlsh());
                rtnData.setFplxdm(invoiceParam.getFplxdm());
                rtnData.setJshj(new BigDecimal(sdQdpkfsfpcc14Rtn.getJshj()));
                rtnData.setHjje(invoiceParam.getHjje());
                rtnData.setHjse(invoiceParam.getHjse());
                rtnData.setHzxxbbh(sdQdpkfsfpcc14Rtn.getXxbbh());

                invoiceRtn.setData(rtnData);
            } else {
                invoiceRtn.setCode(sdQdpkfsfpcc14Rtn.getCode());
                invoiceRtn.setSuccess(false);
                invoiceRtn.setMsg(sdQdpkfsfpcc14Rtn.getMsg());
            }
        }
        return invoiceRtn;
    }

    /**
     * 登录电票平台
     *
     * @param dpdlParam
     * @return
     */
    @Override
    public DpdlRtn login(DpdlParam dpdlParam) {
        SdDldpptrc118Param param = ZySdRequestParamConvert.dpdlParamConvert(dpdlParam);
        String response = zhiyunSdApiCallUtil.requestStr(APIURL.login.url, param, dpdlParam.getKpzd().getDzswjzh());
        //转换开票结果
        return ZySdResponseRtnConvert.loginRtnConvert(dpdlParam, response);
    }

    /**
     * 获取是否需要人脸识别
     *
     * @param faceParam
     * @return
     */
    @Override
    public SdHqsfxyrlsbcc120Rtn getFaceState(SdHqsfxyrlsbrc120Param faceParam) {
        String response = zhiyunSdApiCallUtil.requestStr(APIURL.getFaceState.url, faceParam, faceParam.getKpzd().getDzswjzh());
        //更新终端对应的电票平台在线状态
        updateZdzt(faceParam.getKpzd(), response);
        //转换开票结果
        return ZySdResponseRtnConvert.faceStateRtnConvert(response);
    }

    /**
     * 获取人脸二维码
     *
     * @param faceImgParam
     * @return
     */
    @Override
    public FaceImgRtn getFaceImg(FaceImgParam faceImgParam) {
        List<BasicNameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("nsrsbh", faceImgParam.getNsrsbh()));
        params.add(new BasicNameValuePair("type", faceImgParam.getType()));
        ZhiyunSdApiResponse response = zhiyunSdApiCallUtil.getRequest(APIURL.faceImg.url, params, faceImgParam.getKpzd().getDzswjzh());
        //更新终端对应的电票平台在线状态
        updateZdzt(faceImgParam.getKpzd(), response);
        //转换开票结果
        return ZySdResponseRtnConvert.faceImgRtnConvert(response);
    }

    /**
     * 获取授信额度
     *
     * @param nsrsbh
     * @param commonParam
     * @return
     */
    @Override
    public CreditRtn getCreditLine(String nsrsbh, CommonParam commonParam) {
        DpdlParam param = new DpdlParam();
        param.setNsrsbh(nsrsbh);
        param.setUsername(commonParam.getKpzd().getDzswjzh());
        ZhiyunSdApiResponse response = zhiyunSdApiCallUtil.request(APIURL.creditLine.url, param, commonParam.getKpzd().getDzswjzh());
        //更新终端对应的电票平台在线状态
        updateZdzt(commonParam.getKpzd(), response);
        //转换结果
        return ZySdResponseRtnConvert.creditLineRtnConvert(response, commonParam);
    }

    /**
     * 企业风险查询
     *
     * @param dpdlParam
     * @return
     */
    @Override
    public SdQyfxcxcc116Rtn getCompanyFxcx(DpdlParam dpdlParam) {
        SdDldpptrc118Param param = ZySdRequestParamConvert.dpdlParamConvert(dpdlParam);
        String response = zhiyunSdApiCallUtil.requestStr(APIURL.getCompanyMsg.url, param, dpdlParam.getKpzd().getDzswjzh());
        //更新终端对应的电票平台在线状态
        updateZdzt(dpdlParam.getKpzd(), response);
        //转换结果
        return ZySdResponseRtnConvert.sdQyfxcxcc116RtnConvert(response);
    }

    /**
     * 申请全电票红字信息表
     *
     * @param param
     * @return
     */
    @Override
    public SdSqqdphzxxbcc13Rtn hzxxbsq(CsXxHzsqjsPage page, CommonParam param) {
        SdSqqdphzxxbrc13Param sdSqqdphzxxbrc13Param = ZySdRequestParamConvert.sdSqqdphzxxbrc13ParamConvert(page);
        String response = zhiyunSdApiCallUtil.requestStr(APIURL.hzxxbsq.url, sdSqqdphzxxbrc13Param, param.getKpzd().getDzswjzh());
        //更新终端对应的电票平台在线状态
        updateZdzt(param.getKpzd(), response);
        //转换结果
        return ZySdResponseRtnConvert.sdSqqdphzxxbcc13RtnConvert(response);
    }

    /**
     * 红字信息表撤销
     *
     * @param param
     * @return
     */
    @Override
    public CommonRtn hzxxbcx(HzxxbcxParam param) {
        SdCxhzxxbrc113Param cxhzxxbrc113Param = ZySdRequestParamConvert.sdCxhzxxbrc113ParamConvert(param);
        String response = zhiyunSdApiCallUtil.requestStr(APIURL.hzxxbcx.url, cxhzxxbrc113Param, param.getKpzd().getDzswjzh());
        //更新终端对应的电票平台在线状态
        updateZdzt(param.getKpzd(), response);
        //转换结果
        return ZySdResponseRtnConvert.commonRtnConvert(response);
    }

    /**
     * 红字信息表确认
     *
     * @param param
     * @return
     */
    @Override
    public CommonRtn hzxxbNotarize(QdpHzxxbqrParam param) {
        String response = zhiyunSdApiCallUtil.requestStr(APIURL.hzxxbNotarize.url, param, param.getKpzd().getDzswjzh());
        //更新终端对应的电票平台在线状态
        updateZdzt(param.getKpzd(), response);
        //转换结果
        return ZySdResponseRtnConvert.commonRtnConvert(response);
    }

    /**
     * 红字信息表同步
     *
     * @param param
     * @return
     */
    @Override
    public CommonRtn hzxxbtb(HzxxbtbParam param) {
        SdHzxxbtbrc114Param sdHzxxbtbrc114Param = ZySdRequestParamConvert.sdHzxxbtbrc114ParamConvert(param);
        String response = zhiyunSdApiCallUtil.requestStr(APIURL.hzxxbtb.url, sdHzxxbtbrc114Param, param.getKpzd().getDzswjzh());
        //更新终端对应的电票平台在线状态
        updateZdzt(param.getKpzd(), response);
        //转换结果
        return ZySdResponseRtnConvert.commonRtnConvert(response);
    }

    /**
     * 查询红字信息表
     *
     * @param param
     * @return
     */
    @Override
    public SdCxhzxxbcc112Rtn queryHzxxb(HzxxbtbParam param) {
        SdCxhzxxbrc112Param sdCxhzxxbrc112Param = ZySdRequestParamConvert.sdCxhzxxbrc112ParamConvert(param);
        String response = zhiyunSdApiCallUtil.requestStr(APIURL.getCompanyMsg.url, sdCxhzxxbrc112Param, param.getKpzd().getDzswjzh());
        //更新终端对应的电票平台在线状态
        updateZdzt(param.getKpzd(), response);
        //转换结果
        return ZySdResponseRtnConvert.sdCxhzxxbcc112RtnConvert(response);
    }

    /**
     * 全电票开负数发票
     *
     * @param param
     * @return
     */
    @Override
    public SdQdpkfsfpcc14Rtn hzfpkj(HzfpkjParam param) {
        String sdjk_use_test = sysDictService.queryDictTextByKey("xxparams", "sdjk_use_test");
        SdQdpkfsfprc14Param sdQdpkfsfprc14Param = ZySdRequestParamConvert.sdQdpkfsfprc14ParamConvert(param);
        String response;
        if (!"1".equals(sdjk_use_test)) {
            response = zhiyunSdApiCallUtil.requestStr(APIURL.hzfpkj.url, sdQdpkfsfprc14Param, param.getKpzd().getDzswjzh());
        } else {
            //cwgx todo:全电负数开具模拟数据
            response = "{\"code\":200,\"msg\":\"负数发票开具成功(模拟数据)\",\"message\":\"负数发票开具成功(模拟数据)\",\"data\":{\"fphm\":\"23412000000036511263\",\"kprq\":\"" + DateUtils.now() + "\",\"xhdwsbh\":\"91410100MACTMP4H82\",\"ghdwsbh\":\"91658956859656265\",\"xhdwmc\":\"河南金税软件有限公司\",\"ghdwmc\":\"河南张三客有限公司\",\"jshj\":-1.0,\"xxbbh\":\"41018823101001701086\"},\"total\":0}";
        }
        //更新终端对应的电票平台在线状态
        updateZdzt(param.getKpzd(), response);
        //转换结果
        return ZySdResponseRtnConvert.sdQdpkfsfpcc14RtnConvert(response);
    }

    /***
     * 获取数电纸质发票当前发票号、发票代码
     *
     * @params param
     */
    public CurrentFphmRtn getCurrentFphm(CurrentFphmParam param) {
        SdHqqdzzfpdmhmrc123Param sdHqqdzzfpdmhmrc123Param = new SdHqqdzzfpdmhmrc123Param();
        sdHqqdzzfpdmhmrc123Param.setNsrsbh(param.getKpzd().getNsrsbh());
        sdHqqdzzfpdmhmrc123Param.setZpFppzDm(param.getFplxdm());
        String response = zhiyunSdApiCallUtil.requestStr(APIURL.obtainNoticNumber.url, sdHqqdzzfpdmhmrc123Param, param.getKpzd().getDzswjzh());
        //更新终端对应的电票平台在线状态
        updateZdzt(param.getKpzd(), response);
        //转换结果
        return ZySdResponseRtnConvert.SdHqqdzzfpdmhmcc123RtnConvert(response);
    }

    /**
     * 获取版式文件
     *
     * @param qdbsxzParam
     * @return
     */
    @Override
    public SdHqbswjcc15Rtn getInvoicePdfOfd(QdbsxzParam qdbsxzParam) {
        SdHqbswjrc15Param param = ZySdRequestParamConvert.sdQdpkfsfprc14ParamConvert(qdbsxzParam);
        String response = zhiyunSdApiCallUtil.requestStr(APIURL.getInvoicePdfOfd.url, param, qdbsxzParam.getKpzd().getDzswjzh());
        //更新终端对应的电票平台在线状态
        updateZdzt(qdbsxzParam.getKpzd(), response);
        //转换结果
        SdHqbswjcc15Rtn rtn = new SdHqbswjcc15Rtn();
        if (StringUtils.isNotEmpty(response)) {
            ZhiyunApiResponse zhiyunApiResponse = JSONObject.parseObject(response, ZhiyunApiResponse.class);
            Integer code = zhiyunApiResponse.getCode();
            if (code == 200) {
                JSONObject data = zhiyunApiResponse.getData();
                if ("4".equals(param.getDownflag())) {
                    rtn.setOfdUrl(data.getString("ofdUrl"));
                    rtn.setPdfUrl(data.getString("pdfUrl"));
                    rtn.setXmlUrl(data.getString("xmlUrl"));
                } else {
                    rtn.setData(String.valueOf(data));
                }
                rtn.setSuccess(true);
                rtn.setMsg(zhiyunApiResponse.getMsg());

            } else {
                rtn.setSuccess(false);
                rtn.setMsg(zhiyunApiResponse.getMsg());
            }
        } else {
            rtn.setSuccess(false);
            rtn.setMsg("电票平台接口调用超时，请稍后重试");
        }
        return rtn;
    }

    /**
     * 查询可修复的发票数据
     *
     * @param fpxfParam
     * @return
     */
    @Override
    public SdCxkxfdfpsjcc121Rtn cxkxffp(FpxfParam fpxfParam) {
        SdCxkxfdfpsjrc121Param param = ZySdRequestParamConvert.sdCxkxfdfpsjrc121ParamConvert(fpxfParam);
        String response = zhiyunSdApiCallUtil.requestStr(APIURL.cxkxffp.url, param, fpxfParam.getKpzd().getDzswjzh());
        //更新终端对应的电票平台在线状态
        updateZdzt(fpxfParam.getKpzd(), response);
        //转换结果
        SdCxkxfdfpsjcc121Rtn rtn = new SdCxkxfdfpsjcc121Rtn();
        if (StringUtils.isNotEmpty(response)) {
            ZhiyunApiResponse zhiyunApiResponse = JSONObject.parseObject(response, ZhiyunApiResponse.class);
            Integer code = zhiyunApiResponse.getCode();
            if (code == 200) {
                JSONObject data = zhiyunApiResponse.getData();
                rtn = data.toJavaObject(SdCxkxfdfpsjcc121Rtn.class);
                rtn.setSuccess(true);
                rtn.setMsg(zhiyunApiResponse.getMsg());
            } else {
                rtn.setSuccess(false);
                rtn.setMsg(zhiyunApiResponse.getMsg());
            }
        } else {
            rtn.setSuccess(false);
            rtn.setMsg("电票平台接口调用超时，请稍后重试");
        }
        return rtn;
    }

    @Override
    public SdFjxxBusinessRtn fjxxBusiness(SdFjxxBusinessParam param) {
        String response = zhiyunSdApiCallUtil.requestStr(APIURL.fjxx.url, param, param.getKpzd().getDzswjzh());
        SdFjxxBusinessRtn rtn = new SdFjxxBusinessRtn();
        if (StringUtils.isNotEmpty(response)) {
            SdFjxxBusinessRtn fjxxBusinessRtn = JSONObject.parseObject(response, SdFjxxBusinessRtn.class);
            if("200".equals(fjxxBusinessRtn.getCode())){
                rtn = fjxxBusinessRtn;
                rtn.setSuccess(true);
                rtn.setMsg(fjxxBusinessRtn.getMsg());
            }else{
                rtn.setSuccess(false);
                rtn.setMsg(fjxxBusinessRtn.getMsg());
            }
        } else {
            rtn.setSuccess(false);
            rtn.setMsg("电票平台接口调用超时，请稍后重试");
        }
        return rtn;
    }

    @Override
    public SdFjxxQueryBusinessRtn fjxxQueryBusiness(SdFjxxBusinessParam param) {
        String response = zhiyunSdApiCallUtil.requestStr(APIURL.fjxx.url, param, param.getKpzd().getDzswjzh());
        SdFjxxQueryBusinessRtn rtn = new SdFjxxQueryBusinessRtn();
        if (StringUtils.isNotEmpty(response)) {
            SdFjxxQueryBusinessRtn rtn1 = JSONObject.parseObject(response, SdFjxxQueryBusinessRtn.class);
            if("200".equals(rtn1.getCode())){
                rtn.setData(rtn1.getData());
                rtn.setSuccess(true);
                rtn.setMsg(rtn1.getMsg());
            }else{
                rtn.setSuccess(false);
                rtn.setMsg(rtn1.getMsg());
            }
        } else {
            rtn.setSuccess(false);
            rtn.setMsg("电票平台接口调用超时，请稍后重试");
        }
        return rtn;
    }
}
